package com.easy.leetcode.array;

import java.util.Arrays;

/**
 * @ClassName LargestSumAfterKNegations1005
 * @Description 1005. K 次取反后最大化的数组和
 * @Author zheng
 * @Date 2021/12/3 16:13
 * @Version 1.0
 **/
public class LargestSumAfterKNegations1005 {
    public int largestSumAfterKNegations(int[] nums, int k) {
        Arrays.sort(nums);
        if (k > 0) {
            nums[0] = -nums[0];
            largestSumAfterKNegations(nums, --k);
        }
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }
        return sum;
    }

    public int largestSumAfterKNegations1(int[] nums, int k) {
        Arrays.sort(nums);
        for (int i = 0; i < nums.length && k > 0; i++) {
            if (nums[i] < 0) {
                nums[i] = -nums[i];
                k--;
            } else {
                break;
            }
        }
        Arrays.sort(nums);
        if (k > 0 && k % 2 != 0) {
            nums[0] = -nums[0];
        }
        return Arrays.stream(nums).sum();
    }

    public static void main(String[] args) {
        LargestSumAfterKNegations1005 largestSumAfterKNegations1005 = new LargestSumAfterKNegations1005();
        System.out.println(largestSumAfterKNegations1005.largestSumAfterKNegations1(new int[]{2, -3, -1, 5, -4}, 2));
    }
}
